<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>股指期货数据</title>
    <style>
        .container {
            margin: 0px auto;
            padding: 0px 30px;
            background: #f8f9fa;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .query-panel {
            display: flex;
            gap: 15px;
            margin-bottom: 5px;
            align-items: center;
            padding: 15px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.05);
        }
        select, input[type="date"], button {
            padding: 8px 15px;
            border: 1px solid #ced4da;
            border-radius: 6px;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        select {
            background: #fff;
        }
        input[type="date"] {

        }
        button {
            background: #007bff;
            color: white;
            border-color: #007bff;
            cursor: pointer;
        }
        button:hover {
            background: #0056b3;
            transform: translateY(-1px);
        }
        table {
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
        th {
            background: #f8f9fa;
            font-weight: 600;
        }
        tr:nth-child(even) {
            background: #fcfcfc;
        }
        tr:hover {
            background: #f2f4f6;
        }
        #dataContainer div {
            /** padding: 15px; **/
            border-radius: 6px;
            /** margin: 10px 0;  **/
            font-size: 14px;
        }
        [style*="color: red"] {
            background: #fff5f5;
            border: 1px solid #ffd6d6;
        }
        /*[style*="color: #666"] {*/
        /*    background: #f8f9fa;*/
        /*    border: 1px solid #eee;*/
        /*}*/
    </style>

    <style>
        .group-container {
            margin-bottom: 30px;
            border: 1px solid #eee;
            border-radius: 8px;
            padding: 6px 15px;
            background: #fff;
        }
        .horizontal-group {
            display: flex;
            gap: 5px;
            margin-bottom: 20px;
        }
        .table-container {
            flex: 1;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.05);
        }
        table {
            width: 100%;
            border-collapse: collapse;
            box-shadow: none;
        }
        th {
            background: #f8f9fa;
            font-weight: 600;
            padding: 5px 15px;
            border-bottom: 2px solid #e9ecef;
            text-align: center;
        }
        td {
            padding: 10px 0px;
            border-bottom: 1px solid #eee;
            text-align: center;
        }
        tr:last-child td {
            border-bottom: none;
        }
        tr:hover {
            background: #f8f9fa !important;
        }
        h3 {
            margin: 0 0 1px 0;
            padding: 5px 15px;
            background: #f8f9fa;
            font-size: 15px;
            border-bottom: 1px solid #eee;
            text-align: center;
        }
    </style>

    <style>
        /* 修改状态提示定位方式 */
        #statusContainer {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 100000;
            pointer-events: none;
        }

        .status-box {
            padding: 16px 30px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            font-size: 15px;
        }

        /* 新增状态颜色区分 */
        .status-box.success {
            background: #f0f9eb;
            color: #67c23a;
            border: 1px solid #e1f3d8;
        }

        .status-box.error {
            background: #fef0f0;
            color: #f56c6c;
            border: 1px solid #fde2e2;
        }
    </style>

</head>
<body>
<div class="container">
    <div class="query-panel">
        <div style="display: flex; gap: 15px; flex: 1;">  <!-- 新增父级DIV -->
            <select id="productId">
                <option value="IF">IF-沪深300股指期货</option>
                <option value="IM">IM-中证1000股指期货</option>
                <option value="IC">IC-中证500股指期货</option>
                <option value="IH">IH-上证50股指期货</option>
            </select>
            <select id="partyId">
                <option value="">全部机构</option>
            </select>
            <input type="date" id="searchDate">
            <button onclick="queryData()" id="queryBtn">查询</button>
        </div>
        <div style="flex: 1; text-align: right; padding-right: 20px;">  <!-- 新增右侧兄弟DIV -->
            <span id="stockChangeInfo" style="font-size: 14px; color: #666;"></span>
        </div>
    </div>

    <!-- 修改选项卡容器，增加统计类型切换按钮 -->
    <div class="tab-container" style="margin-bottom: 5px;">
        <button class="tab-btn active" onclick="switchTab('data')">数据</button>
        <button class="tab-btn" onclick="switchTab('stats')">统计</button>
    </div>


    <div id="statusContainer"></div>
    <div id="dataContainer"></div>
</div>

<script>
    // 新增全局变量
    let currentTab = 'data';
    let currentStatsType = 3; // 3表示按股指类型统计，4表示按左右股指统计

    // 检查是否为周末的函数
    function isWeekend(dateStr) {
        const date = new Date(dateStr);
        const day = date.getDay();
        return day === 0 || day === 6; // 0是周日，6是周六
    }

    // 页面加载时初始化选项卡状态
    document.addEventListener('DOMContentLoaded', function() {
        // 确保默认激活数据选项卡
        document.querySelector('.tab-btn[onclick*="data"]').classList.add('active');
        // 新增日期初始化逻辑
        const today = new Date();
        const dateInput = document.getElementById('searchDate');
        dateInput.value = today.toISOString().split('T')[0];
        // 设置最大可选日期为今天
        dateInput.max = today.toISOString().split('T')[0];
        
        // 设置日期变化事件
        dateInput.addEventListener('change', function() {
            if(isWeekend(this.value)) {
                alert('周末无交易数据，请选择工作日日期');
                this.value = today.toISOString().split('T')[0];
            }
        });
        
        // 新增：获取机构列表
        fetch('http://localhost:8110/common/stock/V1/getStockIndexFuturesByDay?searchType=0')
            .then(response => response.json())
            .then(data => {
                const partySelect = document.getElementById('partyId');
                data.data.forEach(item => {
                    const option = document.createElement('option');
                    option.value = item.partyid;
                    option.textContent = item.shortname;
                    partySelect.appendChild(option);
                });
            }).catch(error => {
                console.error('获取机构列表失败:', error);
            });
            
        // 新增：页面加载后自动查询数据
        queryData(); // 触发首次数据加载
    });

    // 修改选项卡切换函数，显示/隐藏统计类型切换按钮
    function switchTab(tab) {
        currentTab = tab;
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.toggle('active', btn.getAttribute('onclick').includes(tab));
        });
        queryData();
    }

    // 新增统计类型切换函数
    function toggleStatsType() {
        currentStatsType = currentStatsType === 3 ? 4 : 3;
        document.getElementById('statsToggleBtn').textContent =
        currentStatsType === 3 ? '按机构统计' : '按股指统计';
        queryData();
    }

    function queryData() {
        const btn = document.getElementById('queryBtn');
        btn.disabled = true;

        // 显示加载状态
        const statusContainer = document.getElementById('statusContainer');
        statusContainer.innerHTML = `
                <div class="status-box loading">
                    <div class="spinner"></div>
                    正在查询中，请稍候...
                </div>
            `;

        const productId = document.getElementById('productId').value;
        const date = document.getElementById('searchDate').value;
        const partyId = document.getElementById('partyId').value;

        // 修改统计接口判断逻辑，添加partyId参数
        const apiUrl = currentTab === 'stats' 
            ? `http://localhost:8110/common/stock/V1/getStockIndexFuturesByDay?date=${date}&productId=${productId}&searchType=${currentStatsType}${partyId ? `&partyId=${partyId}` : ''}`
            : `http://localhost:8110/common/stock/V1/getStockIndexFuturesByDay?productId=${productId}&searchType=2&date=${date}${partyId ? `&partyId=${partyId}` : ''}`;

        fetch(apiUrl)
            .then(response => {
                if (!response.ok) {
                    throw new Error('请求失败，状态码：' + response.status);
                }
                return response.json();
            })
            .then(data => {
                if (currentTab === 'stats') {
                    renderStatsTables(data.data);
                    // 新增：统计选项卡也更新股指信息
                    const klineData = data.data?.[0]?.klineData || '';
                    document.getElementById('stockChangeInfo').innerHTML = klineData.zdf
                        ? `现价:<span style="color: ${klineData.zdf > 0 ? '#f56c6c' : '#67c23a'};font-weight: 500;">
                            ${klineData.close}
                           </span>` +
                        `涨幅:<span style="color: ${klineData.zdf > 0 ? '#f56c6c' : '#67c23a'};font-weight: 500;">
                            ${klineData.zdf}%
                           </span>`
                        : '<span style="color:#666"></span>';
                } else {
                    // 原有数据选项卡逻辑
                    const klineData = data.data?.[0]?.list?.[0]?.list?.[0]?.klineData || '';
                    document.getElementById('stockChangeInfo').innerHTML = klineData.zdf
                        ? `现价:<span style="color: ${klineData.zdf > 0 ? '#f56c6c' : '#67c23a'};font-weight: 500;">
                            ${klineData.close}
                           </span>` +
                        `涨幅:<span style="color: ${klineData.zdf > 0 ? '#f56c6c' : '#67c23a'};font-weight: 500;">
                            ${klineData.zdf}%
                           </span>`
                        : '<span style="color:#666"></span>';

                    renderTables(data.data);
                }

                statusContainer.innerHTML = `
                        <div class="status-box success">
                            ✓ 数据加载成功
                        </div>
                    `;
                setTimeout(() => statusContainer.innerHTML = '', 800);
            })
            .catch(error => {
                statusContainer.innerHTML = `
                        <div class="status-box error">
                            ✗ ${error.message}
                        </div>
                    `;
                document.getElementById('dataContainer').innerHTML = '';
            })
            .finally(() => {
                btn.disabled = false;
            });
    }

    // 新增统计表格渲染函数
    function renderStatsTables(statsData) {
        if (!statsData || statsData.length === 0) {
            document.getElementById('dataContainer').innerHTML = '<div style="color: #666;text-align: center">' +
                '暂无统计数据' +
                '</div>';
            return;
        }

        const productName = document.getElementById('productId').selectedOptions[0].text.replace(/.*?-/, '').trim();
        const dateStr = document.getElementById('searchDate').value;

        // 计算合计值
        const totalBuyVolume = statsData.reduce((acc, row) => acc + (parseInt(row.buyVolume) || 0), 0);
        const totalSellVolume = statsData.reduce((acc, row) => acc + (parseInt(row.sellVolume) || 0), 0);
        const totalOnlySellVolume = statsData.reduce((acc, row) => acc + (parseInt(row.onlySellVolume) || 0), 0);

        let html = `
            <div class="group-container">
                <h2>${dateStr} ${currentStatsType === 3 ? productName : '所有股指期货'} 多空单统计
                 <button id="statsToggleBtn" onclick="toggleStatsType()" style="margin-left: auto;">${currentStatsType === 3 ? '按机构统计' : '按股指统计'}</button>
                </h2>
           
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th onclick="sortTable('shortname')">机构名称 ↑↓</th>
                                <th onclick="sortTable('buyVolume')">多单增减 ↑↓</th>
                                <th onclick="sortTable('sellVolume')">空单增减 ↑↓</th>
                                <th onclick="sortTable('onlySellVolume')">净空单量 ↑↓</th>
                            </tr>
                        </thead>
                        <tbody id="statsTableBody">
                            <!-- 修改：将合计行放在第一行 -->
                            <tr>
                                <td><strong>多空合计</strong></td>
                                <td><strong>${totalBuyVolume === 0 ? '-' : totalBuyVolume}</strong></td>
                                <td><strong>${totalSellVolume === 0 ? '-' : totalSellVolume}</strong></td>
                                <td style="${
                                    totalOnlySellVolume < 0 ? 'color: #67c23a' : 
                                    (totalOnlySellVolume > 0 ? 'color: #f56c6c' : 'color: #333')
                                }"><strong>
                                        ${totalSellVolume-totalBuyVolume} /
                                        ${totalOnlySellVolume === 0 ? '-' : totalOnlySellVolume}
                                    </strong></td>
                            </tr>
                            ${statsData.map(item => `
                                <tr>
                                    <td>${item.shortname || '-'}</td>
                                    <td>${item.buyVolume || '-'}</td>
                                    <td>${item.sellVolume || '-'}</td>
                                    <td style="${
                                        item.onlySellVolume < 0 ? 'color: #67c23a' : 
                                        (item.onlySellVolume > 0 ? 'color: #f56c6c' : 'color: #333')
                                    }">${item.onlySellVolume || '-'}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;
        document.getElementById('dataContainer').innerHTML = html;
        
        // 保存原始数据用于排序
        window.statsTableData = statsData;
        window.currentSortField = '';
        window.sortAscending = false;
    }

    // 新增排序函数
    function sortTable(field) {
        const data = window.statsTableData;
        if (!data) return;

        // 切换排序方向
        if (window.currentSortField === field) {
            window.sortAscending = !window.sortAscending;
        } else {
            window.currentSortField = field;
            window.sortAscending = true;
        }

        // 排序数据
        const sortedData = [...data].sort((a, b) => {
            var valueA = a[field] || '-';
            var valueB = b[field] || '-';
            if (valueA === '-') return 1;  // 总是把a放在后面
            if (valueB === '-') return -1; // 总是把b放在后面
            // 正常排序逻辑
            if (window.sortAscending) {
                return valueA > valueB ? 1 : -1;
            } else {
                return valueA < valueB ? 1 : -1;
            }
        });

        // 计算排序后的合计值
        const totalBuyVolume = sortedData.reduce((acc, row) => acc + (parseInt(row.buyVolume) || 0), 0);
        const totalSellVolume = sortedData.reduce((acc, row) => acc + (parseInt(row.sellVolume) || 0), 0);
        const totalOnlySellVolume = sortedData.reduce((acc, row) => acc + (parseInt(row.onlySellVolume) || 0), 0);

        // 重新渲染表格内容
        const tbody = document.getElementById('statsTableBody');
        tbody.innerHTML = `
            <!-- 修改：将合计行放在第一行 -->
            <tr>
                <td><strong>多空合计</strong></td>
                <td><strong>${totalBuyVolume === 0 ? '-' : totalBuyVolume}</strong></td>
                <td><strong>${totalSellVolume === 0 ? '-' : totalSellVolume}</strong></td>
                <td style="${
                    totalOnlySellVolume < 0 ? 'color: #67c23a' : 
                    (totalOnlySellVolume > 0 ? 'color: #f56c6c' : 'color: #333')
                }"><strong>
                        ${totalSellVolume-totalBuyVolume} /
                        ${totalOnlySellVolume === 0 ? '-' : totalOnlySellVolume}
                    </strong></td>
            </tr>
            ${sortedData.map(item => `
                <tr>
                    <td>${item.shortname || '-'}</td>
                    <td>${item.buyVolume || '-'}</td>
                    <td>${item.sellVolume || '-'}</td>
                    <td style="${
                        item.onlySellVolume < 0 ? 'color: #67c23a' : 
                        (item.onlySellVolume > 0 ? 'color: #f56c6c' : 'color: #333')
                    }">${item.onlySellVolume || '-'}</td>
                </tr>
            `).join('')}
        `;
    }

    function renderTables(groups) {
        let html = '';
        if (!groups || groups.length === 0) {
            document.getElementById('dataContainer').innerHTML = '<div style="color: #666;text-align: center">' +
                '暂无数据' +
                '<div style="display: flex;flex-direction: column;align-items: flex-start;">' +
                '<p>1、当日的股指期货数据需16:20以后同步；节假日是不成交股指期货的</p>' +
                '<p>2、本页面仅展示股指期货前20的排名，目前没有所有机构的持仓排名</p>' +
                '<p>3、数据来源于-中国金融期货交易所(cffex.com.cn)</p>' +
                '<p>4、本页面数据仅供参考，不做投资建议；理财有风险，投资需谨慎；未成年人禁止炒股</p>' +
                '</div>' +
                '</div>';
            return;
        }

        groups.forEach(group => {
            html += `
                <div class="group-container">
                    <h2>${group.instrumentid}</h2>
                    <div class="horizontal-group">
                        ${group.list.map(item => {
                const totalVolume = item.list.reduce((acc, row) => acc + (parseInt(row.volume) || 0), 0);
                const totalVarvolume = item.list.reduce((acc, row) => acc + (parseInt(row.varvolume) || 0), 0);

                // 新增净空单计算逻辑
                const isSellTable = item.listName === '卖单量排名';
                let buyList = group.list.find(i => i.listName === '买单量排名')?.list || [];

                // 新增：计算合计净空单（累加明细行的onlySellNumber）
                const totalOnlySellNumber = isSellTable
                    ? item.list.reduce((acc, row) => acc + (row.onlySellNumber ?? 0), 0)
                    : 0;

                // 修改：添加是否需要显示合计行的判断
                const showTotalRow = item.list.length > 1;

                return `
                            <div class="table-container">
                                <h3>${item.listName}</h3>
                                <table>
                                    <thead>
                                        <tr>
                                            <th>名次</th>
                                            <th>机构名</th>
                                            <th>成交量</th>
                                            <th>增减量</th>
                                            ${isSellTable ? '<th>净空单</th>' : ''}
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${item.list.map(row => {
                    let netPosition = '-';
                    if (isSellTable) {
                        netPosition = row.onlySellNumber !== undefined ? row.onlySellNumber : '-';
                    }

                    return `
                                                        <tr>
                                                            <td onclick="copyCellContent(this)">${row.rank}</td>
                                                            <td onclick="copyCellContent(this)">${row.shortname}</td>
                                                            <td onclick="copyCellContent(this)">${row.volume || '-'}</td>
                                                            <td onclick="copyCellContent(this)">${row.varvolume  || '-'}</td>
                                                            ${isSellTable ? `<td style="${
                    netPosition !== '-' && netPosition < 0 ? 'color: #67c23a' :
                        (netPosition !== '-' && netPosition > 0 ? 'color: #f56c6c' : 'color: #333')
                }">${netPosition}</td>` : ''}
                                                    </tr>
                                                `;
            }).join('')}
                                        ${showTotalRow ? `
                                        <tr>
                                            <td colspan="2">合计</td>
                                            <td>${totalVolume}</td>
                                            <td>${totalVarvolume}</td>
                                            ${isSellTable ? `
                                            <td style="${
                    totalOnlySellNumber < 0 ? 'color: #67c23a' :
                        (totalOnlySellNumber > 0 ? 'color: #f56c6c' : 'color: #333')
                }">${totalOnlySellNumber !== 0 ? totalOnlySellNumber : '-'}</td>` : ''}
                                        </tr>
                                        ` : ''}
                                    </tbody>
                                </table>
                            </div>
                        `;
        }).join('')}
                </div>
            </div>
        `;
    });
    document.getElementById('dataContainer').innerHTML = html;
}

    // 新增复制功能函数
    function copyCellContent(cell) {
        const text = cell.innerText;
        navigator.clipboard.writeText(text).then(() => {
            const statusContainer = document.getElementById('statusContainer');
            statusContainer.innerHTML = `
                    <div class="status-box success">
                        ✓ 已复制: ${text}
                    </div>
                `;
            setTimeout(() => statusContainer.innerHTML = '', 800);
        }).catch(err => {
            statusContainer.innerHTML = `
                    <div class="status-box error">
                        ✗ 复制失败
                    </div>
                `;
        });
    }

</script>
<style>
    /* 新增选项卡样式 */
    .tab-container {
        display: flex;
        gap: 10px;
    }
    .tab-btn {
        padding: 8px 20px;
        border: none;
        border-radius: 6px 6px 0 0;
        background: transparent;
        color: #666;
        cursor: pointer;
        transition: all 0.2s;
    }
    .tab-btn.active {
        background: #007bff;
        color: white;
        transform: none;
        font-weight: bold; /* 新增：加粗文字 */
        box-shadow: 0 0 0 2px rgba(0,123,255,0.3); /* 新增：浅蓝色阴影效果 */
        border-bottom: 3px solid #0056b3; /* 新增：底部高亮蓝边 */
    }
    .tab-btn:hover:not(.active) {
        background: #f8f9fa;
    }

    /* 新增统计切换按钮样式 */
    #statsToggleBtn {
        background: #28a745;
        border-color: #28a745;
        padding: 6px 12px;
        font-size: 12px;
    }
    #statsToggleBtn:hover {
        background: #218838;
        transform: none;
    }
    #statsTypeToggle {
        background: #f8f9fa;
        border-radius: 8px;
    }
</style>

</body>
</html>